package com.wuba.rxjavademo.lyz.day0416;

import rx.Observable;

/**
 * Created by liyaxing on 2016/4/18.
 */
public class Demo05 {

    public static void main(String[] ss) {

        Demo05 demo = new Demo05();
        Observable<Integer> observable = demo.retryWhenObservable();
        observable.subscribe(integer -> print(integer));

    }

    private Observable<Integer> retryWhenObservable() {
        return createObservable().retryWhen(observable ->
                /*observable.zipWith(Observable.just(1,2,3),(o, integer) -> o.getMessage() + integer).map(s -> {
                    print(s) ;
                    return s ;
                }*/
                observable.map(o -> {
                    print(o);
                    return Observable.just(1);
                }));
    }

    private Observable<Integer> retryObservable() {
        return createObservable().retry();
    }

    private Observable<Integer> onExceptionResumeObservable() {
        return createObservable().onExceptionResumeNext(Observable.just(-1, -2));
    }

    private Observable<Integer> onErrorResumeObservable() {
        return createObservable().onErrorResumeNext(throwable -> Observable.just(999));
    }

    private Observable<Integer> createObservable() {
        return Observable.create(subscriber -> {

            for (int i = 0; i < 20; i++) {
                if (i == 3) {
                    subscriber.onError(new Exception("value == 3"));
                } else if (i == 4) {
                    subscriber.onError(new Exception("value == 4"));
                } else if (i == 5) {
                    subscriber.onError(new Exception("value == 5"));
                } else if (i == 6) {
                    subscriber.onError(new Exception("value == 6"));
                } else {
                    subscriber.onNext(i);
                }
            }
            subscriber.onCompleted();

        });
    }

    private static void print(Object obj) {
        System.out.println(obj);
    }

}
